﻿using RabbitMQ.Gateway;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using RabbitMQ.Client;

namespace MyProject.HQ.Consume.Plug
{
    public class CinemaConsumePlug : BaseMessageConsumer
    {
        /***
        因为一个队列只部署了一个消费者，所以不会存在异常消息死循环的问题
        ***/
        public override void ConsumeMessage(Message message, IModel channel, DeliveryHeader header, ILog loger, Func<object, string, string, bool> ErrorMethod)
        {
            object obj = null;
            try
            {
                if (message.Properties.ContentType == Const.PlAIN_OBJ)
                {
                    obj = base.ConvertFromMessageToObject(message);
                }
                else
                {
                    obj = base.ConvertFromMessageToString(message);
                    ErrorMethod(obj.ToString(), "pub_error", "rk_error");
                    channel.BasicAck(header.DeliveryTag, false);
                    return;
                }
            }
            catch (Exception ex)
            {
                //此处不处理错误消息，让消息积压到队列中,便于异常排出
                loger.Fatal("消息消费时反序列化异常");
                loger.Fatal(ex.ToString());
                return;
            }
            try
            {
                #region  队列消费逻辑

                //AccessParam acc = obj as AccessParam;
                //if (!ExecuteMethod(acc.AssemblyKey, acc.ClassName, acc.MethodName, acc))
                //{
                //    ((AccessParam)obj).ErrMsg = "通过反射执行业务逻辑时失败，请确定配置文件是否正确";
                //    if (ErrorMethod(obj, "pub_error", "rk_error"))
                //    {   //异常处理失败则积压到队列中
                //        channel.BasicAck(header.DeliveryTag, false);
                //    }
                //    loger.Error("没取到映射文件:" + acc.AssemblyKey);
                //}
                //else
                //{
                     channel.BasicAck(header.DeliveryTag, false);
                //}
                #endregion
            }
            catch (Exception ex)
            {
                if (ErrorMethod(obj, "pub_error", "rk_error"))
                {
                    channel.BasicAck(header.DeliveryTag, false);
                }
                LogAccessParm(obj);
                loger.Error(ex);
            }
        }
    }
}
